﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using ARchGL.Platform.Core;
using ARchGL.Platform.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Authorization;
using ARchGL.Platform.Qianbian;
using WebApiClient;
using ARchGL.Platform.Qianbian.InputModels;
using Abp.Events.Bus;
using ARchGL.Platform.EventHandlers.Events;
using Newtonsoft.Json;
using Abp.Application.Services;
using ARchGL.Platform.Jianwei;
using ARchGL.Platform.Jianwei.InputModels;
using ARchGL.Platform.Jianwei.ViewModels;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using ARchGL.Platform.Configuration;

namespace ARchGL.Platform.Application
{
    /// <summary>
    /// 千变智慧工地 实现
    /// </summary>
    public class UserRealAppService : PlatformApiLogServiceBase, IUserRealAppService
    {
        #region 实例化
        private const int _Days = -1;

        private readonly IRealServerInfoApi realServerInfoApi;
        private readonly IRealClientInfoApi realClientInfoApi;
        private readonly IConfigurationRoot appConfiguration;
        private readonly IRepository<ApiLogs, Guid> apiLogsRepository;
        private readonly IRepository<TP_ProjectUsers, Guid> tp_projectUsersRepository;
        private readonly IRepository<ProjectUsersRegister, Guid> tp_projectUsersRegisterRepository;
        public IEventBus EventBus { get; set; }
        public UserRealAppService(
            IHostingEnvironment env,
            IRealServerInfoApi _realServerInfoApi,
            IRealClientInfoApi _realClientInfoApi,
            IRepository<ApiLogs, Guid> _apiLogsRepository,
            IRepository<TP_ProjectUsers, Guid> _tp_projectUsersRepository,
            IRepository<ProjectUsersRegister, Guid> _tp_projectUsersRegisterRepository
            )
        {
            appConfiguration = env.GetAppConfiguration();
            realServerInfoApi = _realServerInfoApi;
            realClientInfoApi = _realClientInfoApi;
            apiLogsRepository = _apiLogsRepository;
            tp_projectUsersRepository = _tp_projectUsersRepository;
            tp_projectUsersRegisterRepository = _tp_projectUsersRegisterRepository;
        }

        #endregion

        #region 代理接口

        public ITask<AjaxServerResponse> RegisterUser(RegistUserInput input)
        {
            return realServerInfoApi.RegisterUser(input);
        }

        public ITask<AjaxClientResponse<List<AddPersonDto>>> GetAddPersonList()
        {
            return realClientInfoApi.GetAddPersonList();
        }

        public ITask<AjaxClientResponse> UploadAttendance(EncryptRequestInputBase<UploadAttendanceInput> input)
        {
            return realClientInfoApi.UploadAttendance(input);
        }

        public ITask<AjaxClientResponse<List<DelPersonDto>>> GetDelPersonList()
        {
            return realClientInfoApi.GetDelPersonList();
        }

        public ITask<AjaxClientResponse> FeedBack(FeedBackInput input)
        {
            return realClientInfoApi.FeedBack(input);
        }

        #endregion

        #region 代理接口测试方法

        /// <summary>
        /// 1采集
        /// </summary>
        /// <param name="projectUserIds"></param>
        /// <returns></returns>
        public async Task TestRegisterUser(Guid[] projectUserIds)
        {
            string apiUrl = appConfiguration["Jianwei:RealServerApi"];
            string apiRemark = $"实名制采集注册：{apiUrl}/Regist.Asfx";

            //获取待注册的用户信息
            List<ProjectUsersRegister> userList = await tp_projectUsersRegisterRepository.GetAllListAsync(x => projectUserIds.Contains(x.Id));
            userList.ForEach(async user =>
            {
                var log = Execute<ApiLogs>(async obj =>
                {
                    var request = new RegistUserInput
                    {
                        IdNo = user.IdCard,
                        Address = user.Address,
                        Birthday = user.Birthday.ToString("yyyy-MM-dd"),
                        DevMac = user.SerialNumber,
                        Gender = user.Gender,
                        IdIssue = user.LicenceIssuingAuthority,
                        IdPeriod = user.IdExpiryDate,
                        IdPhoto = user.IdPhoto,
                        InfPhoto = user.InfraRedPhoto,
                        Name = "贺楠洋",
                        Nation = user.Nation,
                        Photo = user.Photo
                    };

                    obj.RequestData = JsonConvert.SerializeObject(request);

                    //调用api完成实名制注册
                    var response = await RegisterUser(request);

                    if (response != null)
                        obj.ResponseData = JsonConvert.SerializeObject(response);
                    else
                        obj.ResponseData = $"response is null";

                }, EnumApiType.实名制采集注册, apiRemark);

                await apiLogsRepository.InsertAsync(log); //记录调用日志

            });
        }

        /// <summary>
        /// 2下发
        /// </summary>
        /// <returns></returns>
        public async Task TestGetAddPersonList()
        {
            string apiUrl = appConfiguration["Jianwei:RealClientApi"];
            string apiRemark = $"实名制人员下发：{apiUrl}/httperver/Service/DevivePacketWebSvr.assx/GetAddPerson";

            AjaxClientResponse<List<AddPersonDto>> response = null;

            var log = Execute<ApiLogs>(async obj =>
            {
                obj.RequestData = "";

                //调用api完成实名制注册
                response = await GetAddPersonList();

                if (response != null)
                {
                    obj.ResponseData = JsonConvert.SerializeObject(response);
                }
                else {
                    obj.ResponseData = $"response is null";
                }
            }, EnumApiType.实名制人员下发, apiRemark);

            await apiLogsRepository.InsertAsync(log); //记录调用日志
        }

        /// <summary>
        /// 3考勤
        /// </summary>
        /// <returns></returns>
        public async Task TestUploadAttendance(UploadAttendanceInput input)
        {
            string apiUrl = appConfiguration["Jianwei:RealClientApi"];
            string apiRemark = $"实名制考勤上传：{apiUrl}/httperver/Service/DevivePacketWebSvr.assx/GetAddPerson";

            var log = Execute<ApiLogs>(async obj =>
            {

                EncryptRequestInputBase<UploadAttendanceInput> request = new EncryptRequestInputBase<UploadAttendanceInput>
                {
                    Source = input
                };
                obj.RequestData = JsonConvert.SerializeObject(input);

                //调用api完成实名制注册
                var response = await UploadAttendance(request);

                if (response != null)
                    obj.ResponseData = JsonConvert.SerializeObject(response);

            }, EnumApiType.实名制考勤上传, apiRemark);

            await apiLogsRepository.InsertAsync(log); //记录调用日志
        }

        /// <summary>
        /// 4删除
        /// </summary>
        /// <returns></returns>
        public async Task TestGetDelPersonList()
        {
            string apiUrl = appConfiguration["Jianwei:RealClientApi"];
            string apiRemark = $"实名制人员删除：{apiUrl}/httperver/Service/DevivePacketWebSvr.assx/GetDelPerson";

            var log = Execute<ApiLogs>(async obj =>
            {

                obj.RequestData = "";

                var response = await GetDelPersonList();

                if (response != null)
                    obj.ResponseData = JsonConvert.SerializeObject(response);


            }, EnumApiType.实名制人员删除, apiRemark);

            await apiLogsRepository.InsertAsync(log); //记录调用日志
        }

        #endregion
    }
}
